//
//  AdjustRequest.swift
//  M4
//
//  Created by jie on 2025/2/27.
//


import Foundation
import NetworkExtension

class AdjustRequest {
    class func M4ReportIpToAdjust() {
        var url = "https://s2s.adjust.com/event"
        
        let params:[String:Any] = [
            "idfa" : M4UserDataManager.m4UserShare.adjustIdfa,
            "event_token" : "f0ob4r",
            "app_token" :  "8yj6r0t9xlvk",
            "s2s" : 1,
            "adid" : M4UserDataManager.m4UserShare.adjustAdid,
            "ip_address" : AdjustRequest.getIPAddress() ?? "",
            "created_at_unix" : Date().timeIntervalSince1970
        ]
        
        url = appendQueryParametersToURL(urlString: url, parameters: params)
        var request = URLRequest(url: URL(string: url)!)
        request.httpMethod = "POST"
        
        URLSession.shared.dataTask(with: request) { data, response, error in
            if error != nil {
                print(error?.localizedDescription ?? "")
            } else if data != nil {
                if let responseString = String(data: data!, encoding: .utf8) {
                    print("Response: \(responseString)")
                }
            }
        }.resume()
    }
    
    
    class func getIPAddress() -> String? {
        var ipAddress: String?
        let host = CFHostCreateWithName(nil, "localhost" as CFString).takeRetainedValue()
        if let addresses = CFHostGetAddressing(host, nil) {
            let addressesArray = addresses.takeUnretainedValue() as NSArray
            if let address = addressesArray.firstObject as? NSData {
                var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                if getnameinfo(address.bytes.assumingMemoryBound(to: sockaddr.self),
                               socklen_t(address.length),
                               &hostname, socklen_t(hostname.count),
                               nil, socklen_t(0), NI_NUMERICHOST) == 0 {
                    ipAddress = String(cString: hostname)
                }
            }
        }
        return ipAddress
    }


    
    class func appendQueryParametersToURL(urlString: String, parameters: [String: Any]) -> String {
        guard var urlComponents = URLComponents(string: urlString) else {
            return urlString
        }
        
        var queryItems: [URLQueryItem] = urlComponents.queryItems ?? []
        
        for (key, value) in parameters {
            let queryItem = URLQueryItem(name: key, value: "\(value)")
            queryItems.append(queryItem)
        }
        
        urlComponents.queryItems = queryItems
        return urlComponents.url?.absoluteString ?? urlString
    }
}
